<?php

namespace App\Http\Controllers\Admin\Message;

use App\Exceptions\MessageException;
use App\Services\Admin\Message\MessageService;
use Exception;
use Illuminate\Http\JsonResponse;

class MessageController extends BaseMessageController
{
    protected MessageService $messageService;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->messageService = $this->loadService('Admin\Message\MessageService');
    }

    /**
     * 公告消息列表
     * @return JsonResponse
     * @throws Exception
     */
    public function list(): JsonResponse
    {

        $list = $this->messageService->list();
        return outputJsonResult($list);
    }

    /**
     * 消息详情
     * @return JsonResponse
     * @throws Exception
     */
    public function detail(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonResult();
        }

        $detail = $this->messageService->detail($this->params);
        return outputJsonResult($detail);
    }

    /**
     * 创建消息
     * @return JsonResponse
     * @throws Exception
     */
    public function create(): JsonResponse
    {
        $rule = [
            'title' => 'required|string|min:1|max:64',
            'describe' => 'string|min:0|max:2000',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonResult();
        }

        $this->messageService->create($this->params);
        return outputJsonResult();
    }

    /**
     * 更新公告消息
     * @return JsonResponse
     * @throws Exception
     */
    public function update(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1',
            'title' => 'string|min:1|max:64',
            'describe' => 'string|min:0|max:2000',
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonResult();
        }

        $this->messageService->update($this->params);
        return outputJsonResult();
    }

    /**
     * 删除公告消息
     * @return JsonResponse
     * @throws MessageException
     */
    public function delete(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonResult();
        }

        $this->messageService->delete($this->params);
        return outputJsonResult();
    }

    /**
     * 上架/下架
     * @return JsonResponse
     * @throws MessageException
     * @throws Exception
     */
    public function release(): JsonResponse
    {
        $rule = [
            'id' => 'required|integer|min:1',
            'status' => 'required|integer|in:0,1'
        ];

        if ($this->ruleCheck($rule)) {
            return outputJsonResult();
        }

        $this->messageService->release($this->params);
        return outputJsonResult();
    }
}
